package com.example.activemq_demo1.com.mmall;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import javax.jws.soap.SOAPBinding;
import java.io.IOException;

/**
 * @ClassName JmsConsumer
 * @Description TODO
 * @Author wushaopei
 * @Date 2019/12/23 22:25
 * @Version 1.0
 */
public class JmsConsumer_Topic {

    public static  final  String ACTIVEMQ_URL = "tcp://49.234.197.103:61616";
    public static  final  String TOPIC_NAME = "activemq_Topic";

    public static void main(String[] args) throws JMSException, IOException {

        System.out.println("*** 我是三号消费者");

        // 1 创建连接工厂，按照给定的url地址，采用默认和用户名和密码
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        // 2 通过连接工厂，获得连接Connection 并启动访问
        Connection connection = activeMQConnectionFactory.createConnection();
        connection.start();
        // 3 创建会话session
        // 两个参数，第一个叫事务，第二个叫签收
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // 4 创建目的地（具体是队列还是主体topic）
        Topic ssss = session.createTopic(TOPIC_NAME);
        // 5 创建消息的生产者
        MessageConsumer messageConsumer = session.createConsumer(ssss);
        // 接收消息
        messageConsumer.setMessageListener(message -> {
            if (null != message && message instanceof  TextMessage){
                TextMessage textMessage = (TextMessage) message;
                try {
                    System.out.println("****消费者接收到Topic消息："+textMessage.getText());
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });

        System.in.read(); // 保证控制台不灭
        messageConsumer.close();
        session.close();
        connection.close();

    }
}
